package top.fsn.invoker;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.rpc.service.GenericService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @Author FSN
 * @Date 2021/3/28 17:24
 */
@Service
public class GenericServiceInvoker {
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private RegistryConfig registryConfig;

    public ReferenceConfig<GenericService> get(String interfaceName) {
        System.out.println("地址:" + registryConfig.getAddress());
        applicationConfig.setRegistry(registryConfig);
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setApplication(applicationConfig);
        reference.setInterface(interfaceName);
        reference.setGroup("demo-dubbo");
        reference.setVersion("1.0");
        reference.setGeneric(true);
        return reference;
    }


    public int invoker(Parameters parameters, String methodName, ReferenceConfig<GenericService> referenceConfig) {
        // 如果返回POJO将自动转成Map
        List<Parameters.Parameter> parameterList = parameters.getParameterList();
        int len = parameterList.size();
        String[] invokeParamTypes = new String[len];
        Object[] invokeParams = new Object[len];
        for(int i = 0; i < len; i++){
            invokeParamTypes[i] = parameterList.get(i).getType();
            invokeParams[i] = parameterList.get(i).getValue();
        }
        return (int) referenceConfig.get().$invoke(methodName, invokeParamTypes, invokeParams);
    }



}
